/**
 * 优化的消息处理API
 * 展示如何使用依赖注入和统一错误处理优化复杂的API逻辑
 */

import { ApiCall } from "tsrpc";
import { ReqMessage, ResMessage } from "../shared/api_bot/PtlMessage";
import { ClientAction } from "../shared/api_bot/IMassage";
import { ApiHelper } from "../infrastructure/api/ApiHelper";
import { createApiContext } from "../infrastructure/di/ServiceContainer";
import { ComType } from "../core/tool/component";

/**
 * 优化的消息处理API
 * 使用依赖注入和结构化错误处理
 */
export default async function OptimizedApiMessage(call: ApiCall<ReqMessage, ResMessage>) {
    // 记录API调用
    ApiHelper.logApiCall(call, 'ApiMessage');
    
    try {
        // 检查Bot消息
        if (call.req.UserInfo.isBot) {
            console.log('不回复bot消息');
            ApiHelper.success(call, { action: ClientAction.none });
            return;
        }
        
        // 记录收到的消息
        logIncomingMessage(call.req);
        
        // 获取玩家
        const player = call.req._player;
        if (!ApiHelper.checkPlayerExists(player, call)) {
            return;
        }
        
        // 创建API上下文
        const context = createApiContext();
        
        // 处理玩家状态
        await handlePlayerState(player);
        
        // 处理场景消息
        await handleSceneMessage(player, call.req, context);
        
        // 返回成功响应
        ApiHelper.success(call, { action: ClientAction.none });
        
    } catch (error) {
        console.error('消息处理失败:', error);
        ApiHelper.internalError(call, '消息处理失败', error as Error);
    }
}

/**
 * 记录收到的消息
 */
function logIncomingMessage(req: ReqMessage): void {
    const messageType = req.Message.private ? '[私信]' : '[群消息]';
    const platform = req.ClientInfo.platform;
    const userName = req.UserInfo.name;
    const clientId = req.ClientInfo.id;
    const content = req.Message.content;
    
    console.log(
        `[收到消息:${platform}]${messageType}id:${userName}cid:(${clientId})\n${content}\n----------`
    );
}

/**
 * 处理玩家状态
 */
async function handlePlayerState(player: any): Promise<void> {
    if (!player) {
        throw new Error('玩家对象不存在');
    }
    
    // 检查玩家是否死亡，如果死亡则复活
    const rpgComponent = player.getComponent(ComType.rpg);
    if (rpgComponent && rpgComponent.isDie()) {
        rpgComponent._clientHandler.client_reLive();
        console.log(`玩家 ${player.id} 已自动复活`);
    }
}

/**
 * 处理场景消息
 */
async function handleSceneMessage(
    player: any, 
    req: ReqMessage, 
    context: any
): Promise<void> {
    // 获取玩家位置
    const posComponent = player.getComponent(ComType.位置);
    if (!posComponent) {
        throw new Error('玩家缺少位置组件');
    }
    
    // 获取场景管理器
    const sceneManager = context.sceneManager;
    const scene = sceneManager.getScene(posComponent.sceneName);
    
    if (!scene) {
        console.warn(`场景不存在: ${posComponent.sceneName}`);
        return;
    }
    
    // 构建消息对象
    const messageData = {
        message: req.Message.content,
        player,
        call: null, // 在新架构中，不直接传递call对象
        Message: req.Message,
        ClientInfo: req.ClientInfo
    };
    
    try {
        // 场景tick和意图分析
        await scene.tick(messageData);
        scene.analysisIntent(messageData);
        
        console.log(`场景 ${posComponent.sceneName} 处理消息完成`);
    } catch (error) {
        console.error(`场景 ${posComponent.sceneName} 消息处理失败:`, error);
        throw error;
    }
}

/**
 * 消息处理结果统计
 */
export class MessageProcessingStats {
    private static stats = {
        totalMessages: 0,
        botMessages: 0,
        successfulMessages: 0,
        failedMessages: 0,
        averageProcessingTime: 0
    };
    
    static recordMessage(
        isBot: boolean, 
        success: boolean, 
        processingTime: number
    ): void {
        this.stats.totalMessages++;
        
        if (isBot) {
            this.stats.botMessages++;
        }
        
        if (success) {
            this.stats.successfulMessages++;
        } else {
            this.stats.failedMessages++;
        }
        
        // 更新平均处理时间
        const totalProcessingTime = this.stats.averageProcessingTime * (this.stats.totalMessages - 1) + processingTime;
        this.stats.averageProcessingTime = totalProcessingTime / this.stats.totalMessages;
    }
    
    static getStats() {
        return { ...this.stats };
    }
    
    static resetStats(): void {
        this.stats = {
            totalMessages: 0,
            botMessages: 0,
            successfulMessages: 0,
            failedMessages: 0,
            averageProcessingTime: 0
        };
    }
}

/**
 * 增强版消息处理API（包含统计功能）
 */
export async function EnhancedApiMessage(call: ApiCall<ReqMessage, ResMessage>) {
    const startTime = Date.now();
    let success = false;
    
    try {
        await OptimizedApiMessage(call);
        success = true;
    } catch (error) {
        success = false;
        throw error;
    } finally {
        const processingTime = Date.now() - startTime;
        MessageProcessingStats.recordMessage(
            call.req.UserInfo.isBot,
            success,
            processingTime
        );
    }
}
